//
// Created by hjie on 23-8-13.
//

#include "rtp_parser.h"

RtpParser::RtpParser()
{

}

bool RtpParser::IsRtpPacket(uint8_t *data)
{
    return true;
}

bool RtpParser::ParseRtpFrame(uint8_t *data, int length, int &use_length, RtpFrame & rtp_frame)
{
    if (length < 12)
    {
        return false;
    }
    // 判断包是否为rtp包
    bool result = ParseRtpHeaderFrame(data, length, use_length, rtp_frame.m_header);
    if (result)
    {
        length = length - use_length;
        int data_use_length = 0;
        result = ParesRtpDataFrame(data + use_length, length, data_use_length, rtp_frame.m_data);
        if (result)
        {
            use_length += data_use_length;
        }
    }
    return result;
}

bool RtpParser::ParseRtpHeaderFrame(uint8_t *data, int length, int &use_length, RtpHeaderFrame &header)
{
    header.m_version = (data[use_length] & (0b11000000)) >> 6;
    header.m_padding = (data[use_length] & (0b00100000)) >> 5;
    header.m_extension = (data[use_length] & (0b00010000)) >> 4;
    header.m_contributing_sources = data[use_length] & (0b00001111);

    use_length += 1;
    header.m_marker = (data[use_length] & (0b10000000)) >> 7;
    header.m_payload_type = data[use_length] & (0b01111111);

    use_length += 1;
    memcpy(&header.m_sequence_number, data + use_length, sizeof(header.m_sequence_number));
    header.m_sequence_number = be16toh(header.m_sequence_number);

    use_length += 2;
    memcpy(&header.m_timestamp, data + use_length, sizeof(header.m_timestamp));
    header.m_timestamp = be32toh(header.m_timestamp);

    use_length += 4;
    memcpy(&header.m_ssrc, data + use_length, sizeof(header.m_ssrc));

    bool result = true;
    use_length += 4;
    if (header.m_contributing_sources > 0 && (header.m_contributing_sources * 4) <= (length - use_length))
    {
        uint32_t csrc{0};
        for (int index = 0; index < header.m_contributing_sources; index++)
        {
            memcpy(&csrc, data + use_length, sizeof(csrc));
            header.m_csrc_vec.push_back(csrc);

            use_length += 4;
        }
        result = true;
    }
    else
    {
        result = header.m_contributing_sources == 0;
    }
    if (result && header.m_extension)
    {
        // 暂时不处理extension内容
    }
    return result;
}

bool RtpParser::ParesRtpDataFrame(uint8_t *data, int length, int &use_length, RtpDataFrame &rtp_data)
{

    return true;
}

